/**
 * 问卷调查
 * @author zhangiang
 * @date   2016/10/26
 */

import PullRefresh from '../components/mui/PullRefresh.js';
import NoData from '../components/NoData.js';

(function (lf, r) {
    var ajax = lf.utils.ajax,
        fmt = 'yyyy-MM-dd',
        doAction = lf.bridgeJs.doAction,
        getUrlParam = lf.utils.getUrlParam,
        appAlert = lf.bridgeJs.alert,
        mark = -0,
        from = '',
        mask = 0,
        arr = [],
        radioText = '',//答案id单选
        radioId = '',//问题id
        gradeText = '',//答案id打分
        gradeId = '',//问题id
        RC = r.createClass;

    const questionnaireId = getUrlParam('questionnaireId');//详情需要

    var Mask = RC({//遮罩层
        getInitialState: function () {
            return ({
                show: true,
            })
        },

        clickFn: function () {
            this.setState({
                show: !this.state.show,
            })
            lf.bridgeJs.doClose();
        },

        render: function () {
            return (
                <div>
                    <div className={"page-text to-te " + (!this.state.show?'hide':'')}>
                        <div className="center-box">
                            <p className="title">提示：</p>
                            <div className="explain">{this.props.peroration||'谢谢您的参与！'}</div>
                            <div onTouchEnd={this.clickFn} className="test-btn">确认</div>
                        </div>
                    </div>
                </div>
            )
        }
    })

    var Choose = RC({//单选 1
        getInitialState: function () {
            return ({
                nextOperator: '',
                answer: '',
            })
        },

        handleChange: function (event) {
            this.props.getData(radioText, radioId, (event && event.target.value));
        },

        componentDidMount: function () {
            var single = $('.single-one'),
                me = this;
            $.each(single, function (i, item) {//单选
                var $me = $(this);
                $me.off();
                $me.on('touchstart', function () {
                    var nextOperator = $(this).data('wd');//问题id
                    var answer = $(this).data('id');//答案 id
                    radioText = nextOperator;
                    radioId = answer;
                    let content = $('.radioText').val();
                    console.log('2: ' + JSON.stringify(content))
                    me.props.getData(radioText, radioId, content);
                });
            });
        },

        render: function () {
            var store = this.props.data;
            return (
                <div>
                    <div className="input single-one" data-id={store.id} data-wd={store.subjectId}>
                        <input type="radio" name="score1" id="10"/>
                        <label className="text-rg" for="10">{store.itemName}</label>
                        {store.inputStatus == '2' ?
                            <input type="text" onChange={this.handleChange} className="radioText"/> : null}
                    </div>
                </div>
            )
        }

    })

    var Check = RC({//多选 2
        getInitialState: function () {
            return ({
                enough: '',//答案
                subject: '',
                stored: []
            })
        },
        componentDidMount: function () {
            var anarchy = $('.anarchy'),//勾选
                checkText = $('.checkText'),//输入框
                infn = '',
                me = this;
            var into = [];
            // var stored = [];
            $.each(anarchy, function () {
                var $me = $(this);
                // console.log('in')
                // let into = [];
                $me.off();
                $me.on('touchstart', function (e) {
                    if(e.target.className == 'checkNo'||e.target.className == 'text-rg'){
                        into = [];
                        $me.toggleClass('active');
                        var were = $('.choose').find('.active');
                        for (var i = 0; i < were.length; i++) {
                            into.push(were.eq(i).data('id'));
                        }
                        //let storedAdd = into.join(';');
                        let subject = $me.data('wd');
                        infn = subject;
                        //me.state.subject = subject;
                        //me.state.enough = storedAdd; //答案
                        //let sendData = '';
                        //into.map((info,i)=>{
                        //    sendData+= info+','+stored[i]+',';
                        //})
                        //console.log(sendData)
                       // me.props.getCheck(infn,'');
                    }
                })
            })

            $.each(checkText, function () {
                var $me = $(this);
                $me.off();
                $me.on('blur', function (e) {
                    let stored = [];
                    if(e.target.className == 'checkText') {
                        $me.toggleClass('focus');
                        var were = $('.choose').find('.focus');
                        for (var i = 0; i < were.length; i++) {
                            stored.push(were.eq(i).val());
                        }
                        let storedAdd = stored.join(',');
                        console.log('./////////////////');
                        console.log(stored)
                        me.state.enough = storedAdd; //答案
                        let sendData = '';
                        // console.log(into)
                        into.map((info,i)=>{
                            sendData+= info+','+stored[i]+',';
                        })
                        me.props.getCheck(infn, sendData);
                    }
                })
            })
        },

        render: function () {
            var store = this.props.data;
            return (
                <div>
                    <div className="input anarchy" data-id={store.id} data-wd={store.subjectId}>
                        <input type="checkbox" name="score1" id="10" className="checkNo"/>
                        <label className="text-rg" for="10">{store.itemName}</label>
                        {store.inputStatus == '2' ?
                            <input type="text" onChange={this.handleChange} className="checkText"/> : null}
                    </div>
                </div>
            )
        }

    })

    var Text = RC({//输入框3
        getInitialState: function () {
            return ({
                textAction: '',
            })
        },
        handleChange: function (event) {
            this.props.getText(from, '', event.target.value);
        },

        componentDidMount: function () {
            var required = $('.required'),//输入框
                me = this;
            $.each(required, function () {
                var $me = $(this);
                $me.off();
                $me.on('touchstart', function () {
                    var Action = $me.data('wd');
                    from = Action;
                })
                $me.on('keyup', function () {
                    var L = $(this).val().length;
                    if (L > 100) {
                        $(this).val($(this).val().substring(0, 100));
                    }
                })
            })
        },

        render: function () {
            var store = this.props.data;
            return (
                <div>
                    <textarea data-wd={store.subjectId} className="required" name="" id="" cols="30" rows="10"
                              onChange={this.handleChange} onkeyup="checkLen(this)" placeholder='限100字'></textarea>
                </div>
            )
        }

    })

    var Rates = RC({//打分题 4
        getInitialState: function () {
            return ({
                answer: '',
                nextOperator: '',
            })
        },

        handleChange: function (event) {
            this.props.getData(gradeText, gradeId, (event && event.target.value));
        },
        componentDidMount: function () {
            var single = $('.single'),
                me = this;
            $.each(single, function (i, item) {//单选 打分
                var $me = $(this);
                $me.off();
                $me.on('touchstart', function () {
                    var nextOperator = $(this).data('wd');//问题id
                    var answer = $(this).data('id');//答案 id
                    gradeText = nextOperator;
                    gradeId = answer;
                    let content = $('.radioAdd').val();
                    console.log($('.radioAdd').val());
                    console.log('2: ' + JSON.stringify(content))
                    me.props.getData(gradeText, gradeId, content);
                });
            });
        },

        render: function () {
            var store = this.props.data;
            return (
                <div>
                    <div className="input single" data-id={store.id} data-wd={store.subjectId}>
                        <input type="radio" name="score1" id="10" className="radioNO"/>
                        <label className="text-rg" for="10"><span className="desc">{store.itemDesc}<span>分</span></span>
                            <span>{store.itemName}</span></label>
                        {store.inputStatus == '2' ?
                            <input type="text" onChange={this.handleChange} className="radioAdd"/> : null}
                    </div>
                </div>
            )
        }

    })

    var ListGroup = RC({
        getInitialState: function () {
            return ({
                houseNum: '',
            })
        },

        render: function () {
            let subject = this.props.data;
            let me = this;
            if (subject.questionType == '1') {
                var init = subject.items.map(function (e, i) {
                    return <Choose key={i} data={e} getData={me.props.getData}/>
                })
            } else if (subject.questionType == '2') {
                var init = subject.items.map(function (e, i) {
                    return <Check key={i} data={e} getCheck={me.props.getCheck}/>
                })
            } else if (subject.questionType == '3') {
                var init = <Text data={subject} getText={me.props.getText}/>
            } else if (subject.questionType == '4') {
                var init = subject.items.map(function (e, i) {
                    return <Rates key={i} data={e} getData={me.props.getData}/>
                })
            }

            return (
                <div>
                    <div className="scores">
                        <div className="top-text">{subject.catoryDesc}</div>
                        <div className="title">{subject.subjectDesc}
                            <span>{subject.questionType == '1' ? '(单选)' : subject.questionType == '2' ? '(多选)' : subject.questionType == '4' ? '(单选)' : null}</span>
                        </div>
                        <div className="choose">
                            {init}
                        </div>
                    </div>
                </div>
            )
        }
    })

    var Body = RC({
        getInitialState: function () {
            return ({
                data: [],//获取ajax
                wrong: '',//问题id
                answer: '',//答案id
                size: '',//总问题数量
                liked: '1',//序号
                nextId: '',
                id: '',
                content: '',
                peroration: '',
                show: true,
            })
        },

        componentWillMount: function () {
            var me = this,
                dataAdd = [];
            ajax({
                type: 'post',
                data: {
                    questionnaireId: questionnaireId,
                },
                success: function (data) {
                    for (var i = 0; i < data.dataList.length; i++) {
                        if (data.dataList[i].questionType != '') {
                            dataAdd.push(data.dataList[i])
                        }
                    }
                    console.log(data)
                    me.setState({
                        data: dataAdd,
                        size: dataAdd.length,
                    })
                    arr = new Array(me.state.size);
                }
            }, lf.finger.api.survey.getSubjectsAndItems);

            ajax({///答题结束提示语
                type: 'post',
                data: {
                    questionnaireId: questionnaireId,
                },
                success: function (data) {
                    this.setState({
                        peroration: data.data.peroration,
                    })
                }.bind(me)
            }, lf.finger.api.survey.getQuestionnaireInfo);

        },

        getCheck(nextId, idText){//多选 内容框
            arr[mask] = nextId;//判断有没有做题
            this.setState({
                nextId: nextId,
                id: idText,
                content: '',//content,
            })
        },

        getData(nextId, id, content){//单选 打分
            arr[mask] = nextId;//判断有没有做题
            var contentId = content == false ? id : id+','+content+';';// 判断有没有输入 内容
            this.setState({
                nextId: nextId,
                id: contentId,
                content: '',//content,
            })
        },

        getText(nextId, id, content){//输入框
            arr[mask] = nextId;//判断有没有做题
            this.setState({
                nextId: nextId,
                id: id,
                content: content,
            })
        },


        handleClick: function () {
            this.setState({liked: this.state.liked <= this.state.size - 1 ? ++this.state.liked : this.state.liked});
        },
        prevClick: function () {
            this.setState({liked: this.state.liked >= 2 ? --this.state.liked : this.state.liked});
        },
        componentDidUpdate: function () {
        },

        componentDidMount: function () {
            var me = this,
                user = this.props.user;
            $('.prev').on('tap', function () {
                --mask;
                me.prevClick();
                if (mark == 0) {
                    mark = 0
                    return
                } else {
                    ++mark
                }
                me.motion($(window).width());
            })


            console.log(me.state.nextId + '888')
            console.log(me.state.id + '888')
            console.log(me.state.content + '888')
            $('.next').on('tap', function () {
                // $('body').trigger('touchstart');
                //console.log(me.state.nextId + '888')
                //console.log(me.state.id + '888')
                //console.log(me.state.content + '888')
                //
                //var stored = [],
                //    into = [],
                //    sendData;
                //var were = $('.choose').find('.focus');
                //for (var i = 0; i < were.length; i++) {
                //    stored.push(were.eq(i).val());
                //}
                //console.log(stored)
                //
                //var were = $('.choose').find('.active');
                //for (var i = 0; i < were.length; i++) {
                //    into.push(were.eq(i).data('id'));
                //}
                //console.log(into)
                //
                //into.map((info,i)=>{
                //    sendData+= info+','+stored[i]+',';
                //})
                setTimeout(function(){
                    if (arr[mask]) {
                        console.log('通过');
                        ajax({//点击发送内容
                            type: 'post',
                            data: {
                                projectId: user.projectId,
                                userId: user.userId,//员工id
                                subjectId: me.state.nextId,//问题id
                                subjectItemid: me.state.id,  //sendData,,//问题选项id，如是多选，则用‘;’拼接起来。问答题没值 answer单选
                                result: me.state.content,//问答题填写的答案，选择题没值
                            },
                            success: function (data) {
                                console.log(data)
                                var anarchy = $('.anarchy');
                                $.each(anarchy, function () {//多选按钮
                                    var $me = $(this);
                                    $me.removeClass('active');
                                    $me.removeClass('focus');
                                })
                            }
                        }, lf.finger.api.survey.createVotes)
                        me.handleClick();
                        if (mark == -me.state.size + 1) {
                            me.setState({
                                show: !me.state.show
                            })
                            mark = mark;
                            return
                        } else {
                            --mark;
                        }
                        me.motion($(window).width());
                    } else {
                        //console.log('from child: ' + me.state.nextId)
                        //console.log('from child: ' + me.state.id)
                        //console.log('from child: ' + me.state.content)
                        appAlert('请先回答当前题目');
                        return false;
                    }
                    ++mask;
                    //  me.setState({nextId:'',});
                },10)
            })
        },

        motion: function (amount) {
            var quantum = (mark * amount) + 'px';
            $('.toup').css({left: quantum});
        },

        render: function () {
            var data = this.state.data;
            let me = this;
            var subTitle = data.map(function (e, i) {
                return <ListGroup key={i} data={e} getData={me.getData} getText={me.getText} getCheck={me.getCheck}/>
            })
            return (
                <div className='toup'>
                    {subTitle}
                    {!this.state.show ? <Mask peroration={this.state.peroration}/> : ''}
                    <div className='preNexts' ref='preBox'>
                        <div className="order"><span>第</span><span>{this.state.liked}</span>
                            <span>题</span><span>共</span><span>{this.state.size == 0 ? '1' : this.state.size}</span><span>题</span>
                        </div>

                        <div className={'prev '+(this.state.liked == 1?'add':'')} ref='prev'>上一题</div>
                        {
                            this.state.liked == this.state.size ? <div className='next' ref='next'>提交问卷</div> :
                                <div className='next' ref='next'>下一题</div>
                        }
                    </div>
                </div>
            )
        }
    })

    lf.appJs.getUser(function (user) {
        r.render(
            <Body user={user}/>,
            document.getElementById('root'), function () {
                $('html').css({'overflow-x': 'hidden'})
                $('body').css({'overflow-x': 'hidden', 'position': 'absolute',})
            }
        )
    });
})(liefeng, React)


